package com.huluobo.a2204monthparkdemo.sign

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2204monthparkdemo.R
import com.huluobo.a2204monthparkdemo.databinding.ActivitySignBinding
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class SignActivity : BaseActivity<ActivitySignBinding, SIgnViewModel>() {
    override fun initData() {
        viewModel.signStartSuccess.observe(this) {
            ToastUtils.showLong("签到成功")
            SPUtils.getInstance().put(Const.PARAM_IS_SIGN, true)
            binding.signBtn.text = "签退"
        }

        viewModel.signEndSuccess.observe(this) {
            ToastUtils.showLong("签退成功")
            SPUtils.getInstance().put(Const.PARAM_IS_SIGN, false)
            binding.signBtn.text = "签到"
        }
    }

    override fun initView() {
        binding.signHeader.headerTitle.text = "签到/签退"
        binding.signHeader.headerBack.setOnClickListener { finish() }

        if (SPUtils.getInstance().getBoolean(Const.PARAM_IS_SIGN)) {
            binding.signBtn.text = "签退"
        } else {
            binding.signBtn.text = "签到"
        }



        binding.signBtn.setOnClickListener {
            val address = "天津市"
            val time = getTime()
            val map = mutableMapOf<String, Any>()
            if (SPUtils.getInstance().getBoolean(Const.PARAM_IS_SIGN)) {
                map[Const.PARAM_END_ADDRESS] = address
                map[Const.PARAM_END_TIME] = time
                map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_USER_ID)

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.signEnd(body)
            } else {
                map[Const.PARAM_START_ADDRESS] = address
                map[Const.PARAM_START_TIME] = time
                map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_USER_ID)

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.signStart(body)
            }


        }
    }


}